<template>
  <div>
    <el-dialog
      title="新增学科"
      :visible="dialogVisible"
      width="20%"
      @close="closeDialog"
      @open="openbutton"
    >
      <!-- 表单 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="addForm"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="学科名称" prop="subjectName">
          <el-input
            v-model="ruleForm.subjectName"
            placeholder="请输入学科名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="ruleForm.isFrontDisplay"
            active-value="1"
            inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>
      <!-- 结束 -->
      <div class="Footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/subjects.js'
export default {
  name: 'SubjectsAdd',
  props: {
    dialogVisible: {
      type: Boolean
    }
  },
  data () {
    return {
      ruleForm: {
        subjectName: '',
        isFrontDisplay: '1'
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 关闭前的回调
    closeDialog () {
      this.$emit('close-dialog')
      this.$refs.addForm.resetFields()
      this.ruleForm = {
        subjectName: '',
        isFrontDisplay: ''
      }
    },
    // 取消
    cancel () {
      this.resetForm()
    },
    // 新增打开按钮状态为启用状态
    openbutton () {
      this.ruleForm.isFrontDisplay = '1'
    },
    confirm () {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          if (this.ruleForm.id) {
            //修改
            await update(this.ruleForm)
          } else {
            // 新增
            await add(this.ruleForm)
            this.$emit('change-page')
          }
          this.$emit('update-list')
          this.$message.success(`${this.ruleForm.id ? '修改' : '新增'}成功`)
          this.resetForm()
        }
      })
    },
    // 封装清空公共组件
    resetForm () {
      this.closeDialog()
      this.$refs.addForm.resetFields()
      this.ruleForm = {
        subjectName: '',
        isFrontDisplay: ''
      }
    },
    // 子传父点击修改学科列表,回显学科详情
    async updatelist (data) {
      const res = await detail(data)
      // console.log(res.data.isFrontDisplay)
      this.ruleForm = res.data
      this.ruleForm.isFrontDisplay = res.data.isFrontDisplay.toString()
      // console.log(this.ruleForm.isFrontDisplay)
    }
  }
}
</script>

<style scoped lang="less">
.Footer {
  display: flex;
  justify-content: flex-end;
}
</style>
